package com.banggood.upms.converter;

import com.banggood.upms.bean.po.UserTree;
import com.banggood.upms.bean.vo.UserTreeVo;
import com.banggood.upms.common.component.CommonComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XuChuangFeng
 * @date 2017/7/19
 */
@Component
public class UserTreeConverter {

    @Autowired
    private CommonComponent component;

    /**
     * #1，将数据库中的用户跟树的映射关系转换成Map集合
     * #2，判断前端传入的当前元素是否已经存在于数据库中（Map集合），若已存在则将这个元素从map中剔除，不存在则证明这个元素是要添加的，map中剩下的元素就是要删除的
     * @param vo 前端传入的，可以获取到最终调整之后的元素
     * @param preAdjustUserTrees DB中获取的，未调整之前的元素集合
     * @param userTreeIdsForRemove 这次调整将要删除的upms_user_tree表中的主键
     * @param userTreeListForInsert 这次调整将要添加的元素集合
     * @return
     */
    public void prepareAdjustElements(UserTreeVo vo,
                                      List<UserTree> preAdjustUserTrees, List<String> userTreeIdsForRemove, List<UserTree> userTreeListForInsert) {
        if(CollectionUtils.isEmpty(vo.getNewTreeIds())) {
            //没有传入任何的待调整元素，不做任何操作，直接删除已存在的全部元素，等同于取消之前所有的分配
        }
        Map<String, UserTree> preAdjustUserTreeMap = transferToMap(preAdjustUserTrees);
        for(String treeId : vo.getNewTreeIds()) {
            // #1,若这个树的ID已经存在于调整前的集合中，证明这个元素已经是添加过的，不需要做调整
            if(preAdjustUserTreeMap.containsKey(treeId)) {
                preAdjustUserTreeMap.remove(treeId);
            } else {
                userTreeListForInsert.add( preparePO(treeId, vo.getUserId()));
            }
        }
        extractUserTreeIdsForRemove(preAdjustUserTreeMap, userTreeIdsForRemove);
    }

    //将List转化为以treeId为Key，以UpmsUserTree为value的Map
    public Map<String, UserTree> transferToMap(List<UserTree> pos) {
        Map<String, UserTree> preAdjustUserTreeMap = new HashMap<>();
        for(UserTree po : pos) {
            preAdjustUserTreeMap.put(po.getTreeId(), po);
        }
        return preAdjustUserTreeMap;
    }

    private void extractUserTreeIdsForRemove(Map<String, UserTree> preAdjustUserTreeMap, List<String> userTreeIdsForRemove) {
        for(String id : preAdjustUserTreeMap.keySet()) {
            userTreeIdsForRemove.add(preAdjustUserTreeMap.get(id).getUserTreeId());
        }
    }

    public List<UserTree> transferToPersistentList(UserTreeVo vo) {
        List<UserTree> pos = new ArrayList<>();
        for(String id : vo.getNewTreeIds()) {
            pos.add(preparePO(id, vo.getUserId()));
        }
        return pos;
    }

    private UserTree preparePO(String treeId, String userId) {
        UserTree po = new UserTree();
        po.setTreeId(treeId);
        po.setUserId(userId);
        po.setUserTreeId(component.generateId());
        return po;
    }
}
